import { getTargetEl } from '../element/getTargetEl';

/**
 * 获取 element 元素 下的 特定 元素组 或 单个元素
 * @param {Element} node 父级 元素
 * @param {String} queryStr class .str || id #str || str(start Class then id)
 */
function getChildElArr(node, queryStr) {
  //   console.log(node, queryStr);

  let aloj = [];

  let ElArr;
  let search = { searchfor: 'id', done: false };
  let a = ['#', '.'].indexOf(queryStr.slice(0, 1));
  search['searchfor'] = a > -1 ? (a == 0 ? 'id' : 'class') : 'all';

  if (search['searchfor'] == 'class') {
    ElArr = document.getElementsByClassName(queryStr);
    searchParentNode();
  }
  if (search['searchfor'] == 'id') {
    ElArr = document.getElementById(queryStr);
    searchParentNode();
  }

  if (search['searchfor'] == 'all') {
    search['searchfor'] = 'class';
    ElArr = document.getElementsByClassName(queryStr);

    searchParentNode();
    if (search['done'] == false) {
      search['searchfor'] = 'id';
      ElArr = document.getElementById(queryStr);
      searchParentNode();
    }
  }

  function searchParentNode() {
    // console.log(search['searchfor']);
    if (search['searchfor'] == 'id') {
      if (getTargetEl(ElArr, node)['done']) {
        search['done'] = true;

        aloj = ElArr;
      }
    }
    if (search['searchfor'] == 'class') {
      for (let i = 0; i < ElArr.length; i++) {
        if (getTargetEl(ElArr[i], node)['done']) {
          aloj.push(ElArr[i]);
        }
      }
    }

    if (aloj.length > 0) {
      search['done'] = true;
    }
  }
  //   console.log(aloj);
  return aloj;
}

export { getChildElArr };
